package com.neusoft.EYSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.EYSystem.dao.LeaveApplyDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.LeaveApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/leaveApply")
public class LeaveApplyController {
    @Autowired
    private LeaveApplyService leaveApplyService;

    @Autowired
    private LeaveApplyDAO leaveApplyDAO;

    @GetMapping("/page")
    public PageResponseBean<List<ClientLeaveApply>> leaveApplyPage(String name, String expectedReturnTime, String approvalStatus, String applyId, Long page, Long size) {
        return leaveApplyService.leaveApplyPage(name, expectedReturnTime, approvalStatus, applyId, page, size);
    }

    @PostMapping("/approval")
    public ResponseBean<Integer> approvalLeaveApply(LeaveApply leaveApply) {
        return leaveApplyService.approvalLeaveApply(leaveApply);
    }

    @GetMapping("/listReturnNum")
    public ResponseBean<Map<String, Integer>> getLeaveApplyNum() {
        ResponseBean<Map<String, Integer>> response = new ResponseBean<>();
        try {
            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("is_visible",true);
            qw.eq("approval_status", "通过");
            HashMap<String,Integer> count = new HashMap<>();
            // 查询一周内的情况
            for (int i = 0; i < 7; i++) {
                String dateKey = java.time.LocalDate.now().minusDays(i).toString();
                qw.eq("expected_return_time", dateKey);
                List<LeaveApply> list = leaveApplyDAO.selectList(qw);
                count.put(dateKey, list.size());
            }
            response.setStatus(200);
            response.setMsg("记录数量查询成功");
            response.setData(count);
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("记录数量查询失败: " + e.getMessage());
        }
        return response;
    }

    @GetMapping("/listShouldNum")
    public ResponseBean<Map<String, Integer>> listShouldNum() {
        ResponseBean<Map<String, Integer>> response = new ResponseBean<>();
        try {
            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("is_visible",true);
            qw.eq("approval_status", "通过");
            Map<String, Integer> count = new HashMap<>();
            // 查询周内所有已批准的外出申请
            for( int i = 0; i < 7; i++) {
                String dateKey = java.time.LocalDate.now().minusDays(i).toString();
                qw.eq("actual_return_time", dateKey);
                List<LeaveApply> list = leaveApplyDAO.selectList(qw);
                count.put(dateKey, list.size());
            }
            response.setStatus(200);
            response.setMsg("记录数量查询成功");
            response.setData(count);
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("记录数量查询失败: " + e.getMessage());
        }
        return response;
    }

    @GetMapping("/listOutNum")
    public ResponseBean<Map<String, Integer>> listOutNum() {
        ResponseBean<Map<String, Integer>> response = new ResponseBean<>();
        try {
            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("is_visible",true);
            qw.eq("approval_status", "通过");
            Map<String, Integer> count = new HashMap<>();
            // 查询一周内所有已批准的外出申请
            for( int i = 0; i < 7; i++) {
                String dateKey = java.time.LocalDate.now().minusDays(i).toString();
                qw.eq("leave_time", dateKey);
                List<LeaveApply> list = leaveApplyDAO.selectList(qw);
                count.put(dateKey, list.size());
            }
            response.setStatus(200);
            response.setMsg("记录数量查询成功");
            response.setData(count);
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("记录数量查询失败: " + e.getMessage());
        }
        return response;
    }

    @PostMapping("/apply")
    public ResponseBean<Integer> applyLeave(LeaveApply leaveApply) {
        ResponseBean<Integer> response = new ResponseBean<>();
        try {
            leaveApply.setVisible(true);
            leaveApply.setApprovalStatus("待审核");
            int result = leaveApplyDAO.insert(leaveApply);
            if(leaveApply.getApplyId() == null){
                return new ResponseBean<>(400, "外出申请提交失败，可能是数据不完整或重复");
            }
            if (result > 0) {
                response.setStatus(200);
                response.setMsg("外出申请提交成功");
                response.setData(result);
            } else {
                response.setStatus(400);
                response.setMsg("外出申请提交失败，数据不完整或重复");
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("外出申请提交失败: " + e.getMessage());
        }
        return response;
    }

    @GetMapping("/getApproveNumById")
    public ResponseBean<Map<String, Integer>> getLeaveNum(Integer applyId) {
        ResponseBean<Map<String, Integer>> response = new ResponseBean<>();
        try {
            // 获取今天日期
            LocalDate now = LocalDate.now();

            // 统计总数
            Long total = leaveApplyDAO.selectCount(new QueryWrapper<LeaveApply>()
                    .eq("is_visible", true)
                    .eq("apply_id", applyId)
                    .ge("leave_time", now));

            // 统计通过数量
            Long approval = leaveApplyDAO.selectCount(new QueryWrapper<LeaveApply>()
                    .eq("is_visible", true)
                    .eq("apply_id", applyId)
                    .ge("leave_time", now)
                    .eq("approval_status", "通过"));

            // 统计不通过数量
            Long reject = leaveApplyDAO.selectCount(new QueryWrapper<LeaveApply>()
                    .eq("is_visible", true)
                    .eq("apply_id", applyId)
                    .ge("leave_time", now)
                    .eq("approval_status", "不通过"));

            // 统计待审核数量
            Long pending = leaveApplyDAO.selectCount(new QueryWrapper<LeaveApply>()
                    .eq("is_visible", true)
                    .eq("apply_id", applyId)
                    .ge("leave_time", now)
                    .eq("approval_status", "待审核"));

            // 组装结果
            Map<String, Integer> count = new HashMap<>();
            count.put("Total", total.intValue());
            count.put("approval", approval.intValue());
            count.put("reject", reject.intValue());
            count.put("pending", pending.intValue());

            response.setData(count);
            response.setStatus(200);
            response.setMsg("外出申请数量查询成功");
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("外出申请数量查询失败: " + e.getMessage());
        }
        return response;
    }


    @GetMapping("/getReturnNumById")
    public ResponseBean<Map<String, Integer>> getReturnNum(Integer applyId) {
        ResponseBean<Map<String, Integer>> response = new ResponseBean<>();
        try {
            LocalDate now = LocalDate.now();
            LocalDate tomorrow = now.plusDays(1);

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            // 查所有应归队的（审批通过、计划归队时间在 today~tomorrow）
            List<LeaveApply> shouldList = leaveApplyDAO.selectList(
                    new QueryWrapper<LeaveApply>()
                            .eq("is_visible", true)
                            .eq("apply_id", applyId)
                            .eq("approval_status", "通过")
                            .ge("expected_return_time", now)
                            .le("expected_return_time", tomorrow)
            );

            int should = shouldList.size();

            // 实际归队人数
            int actual = 0;
            for (LeaveApply apply : shouldList) {
                String actualReturnTimeStr = apply.getActualReturnTime();
                if (actualReturnTimeStr != null && !actualReturnTimeStr.isEmpty()) {
                    LocalDate actualReturnDate = LocalDateTime.parse(actualReturnTimeStr, dtf).toLocalDate();
                    if (!actualReturnDate.isAfter(now)) { // <= today
                        actual++;
                    }
                }
            }

            Map<String, Integer> count = new HashMap<>();
            count.put("should", should);
            count.put("actual", actual);

            response.setData(count);
            response.setStatus(200);
            response.setMsg("外出申请归队数量查询成功");
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("外出申请归队数量查询失败: " + e.getMessage());
        }
        return response;
    }



    @PostMapping("/deleteLogic")
    public ResponseBean<Integer> deleteLogic(Integer applyId) {
        return leaveApplyService.deleteLogic(applyId);
    }

    @PostMapping("/update")
    public ResponseBean<String> updateLeaveApply(LeaveApply leaveApply) {
        ResponseBean<String> response = new ResponseBean<>();
        try {
            int result = leaveApplyDAO.updateById(leaveApply);
            if (result > 0) {
                response.setStatus(200);
                response.setMsg("外出申请更新成功");
            } else {
                response.setStatus(404);
                response.setMsg("外出申请未找到或未做任何更改");
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("外出申请更新失败: " + e.getMessage());
        }
        return response;
    }

    @PostMapping("/registerReturn")
    public ResponseBean<Integer> registerReturn(LeaveApply leaveApply) {
        return leaveApplyService.registerReturn(leaveApply);
    }
}
